#include "tcpfile.h"
#include "ui_tcpfile.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QNetworkInterface>

TCPFile::TCPFile(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::TCPFile)
{
	ui->setupUi(this);
	this->resize(1200,600);
	this->setWindowTitle("TCP文件传输");

	this->client();
	this->server();
	connect(&timer,&QTimer::timeout,[=](){
		timer.stop();
		this->server_send_data();
	});
	qDebug()<<gethostIp().toUtf8().data();
}

TCPFile::~TCPFile()
{
	delete ui;
}
void TCPFile::server()
{
	ui->lineEdit_server_port->setText("2234");
	tcp_server = new QTcpServer(this);
	tcp_server->listen(QHostAddress::Any,ui->lineEdit_server_port->text().toUShort());
	connect(tcp_server,&QTcpServer::newConnection,[=](){
		tcp_server_socket = tcp_server->nextPendingConnection();
		ui->textEdit_server->append(tcp_server_socket->peerAddress().toString());
	});
}
void TCPFile::client()
{
	ui->pushButton_client_choice_file->setEnabled(false);
	ui->pushButton_client_send_file->setEnabled(false);
	ui->lineEdit_client_ip_port->setText("127.0.0.1:2234");
	//设置对象树
	tcp_client_socket = new QTcpSocket(this);
	connect(tcp_client_socket,&QTcpSocket::readyRead,[=](){
		QByteArray buf = tcp_client_socket->readAll();
		if(is_head)
		{
			file_client.setFileName(QString(buf).section("#*#",0,0));
			client_file_size = QString(buf).section("#*#",1,1).toInt();
			ui->textEdit_client->append(buf);
			ui->progressBar->setMinimum(0);
			ui->progressBar->setMaximum(client_file_size/1024);
			file_client.open(QIODevice::WriteOnly);
			is_head = false;
		}
		else
		{
			qint64 len = file_client.write(buf);
			client_receive_file_size += len;
			ui->progressBar->setValue(client_receive_file_size/1024);
			ui->textEdit_client->append(QString("总大小：%1").arg(client_file_size));
			ui->textEdit_client->append(QString("已接收：%1").arg(client_receive_file_size));
			if(client_receive_file_size == client_file_size)
			{
				file_client.close();
				ui->textEdit_client->append("文件接受完毕");
				tcp_client_socket->disconnectFromHost();
				tcp_client_socket->close();
				client_receive_file_size = 0;
				is_head = true;
			}
		}
	});
}

void TCPFile::on_pushButton_server_choice_file_clicked()
{
	QString file_path = QFileDialog::getOpenFileName(this,"选择文件","C:/Users/admin/Videos");
	if(file_path.isEmpty())
		ui->textEdit_server->append("文件无效");
	else
	{
		QFileInfo info(file_path);
		//格式化文件名称
		file_info_server = QString("%1#*#%2").arg(info.fileName()).arg(info.size());
		ui->textEdit_server->append(file_info_server);
		this->file_server.setFileName(file_path);
		this->file_server.open(QIODevice::ReadOnly);
	}

}


void TCPFile::on_pushButton_server_send_file_clicked()
{
	qint64 len = tcp_server_socket->write(file_info_server.toUtf8());
	if(len > 0)
	{
		ui->textEdit_server->append("头部信息发送成功"+file_info_server.split("#*#")[1]);
		//防止TCP黏包延时发送
		timer.start(20);
	}
	else
	{
		ui->textEdit_server->append("头部信息发送失败");
		this->file_server.close();
	}
}
void TCPFile::server_send_data()
{
	qint64 len = 0;
	qint64 accumulation = 0;
	do
	{
		char buf[4*1024] = {0}; //每次发送数据的大小4K
		len = 0;
		//往文件中读数据
		len = file_server.read(buf,sizeof(buf));
		tcp_server_socket->write(buf, len);
		accumulation += len;
	}while(len > 0);
	if(accumulation == file_info_server.split("#*#")[1].toUShort())
	{
		ui->textEdit_server->append("文件发送完成");
		file_server.close();
		//关闭客户端
		tcp_server_socket->disconnectFromHost();
		tcp_server_socket->close();
	}
}

void TCPFile::on_pushButton_client_connect_clicked()
{
	QString ip = ui->lineEdit_client_ip_port->text().split(":")[0];
	quint16 port = ui->lineEdit_client_ip_port->text().split(":")[1].toUShort();
	tcp_client_socket->connectToHost(QHostAddress(ip),port);
}

void TCPFile::on_pushButton_server_bind_port_clicked()
{
	if(ui->pushButton_server_bind_port->text() == "绑定端口")
	{
		ui->pushButton_server_bind_port->setText("取消绑定");
	}
	else
	{
		ui->pushButton_server_bind_port->setText("绑定端口");
	}
}
QString TCPFile::gethostIp()
{
	QString strIpAddress;

	QList<QNetworkInterface> interfaceList = QNetworkInterface::allInterfaces();
	foreach(QNetworkInterface interfaceItem, interfaceList)
	{
		if(interfaceItem.flags().testFlag(QNetworkInterface::IsUp)
				&&interfaceItem.flags().testFlag(QNetworkInterface::IsRunning)
				&&interfaceItem.flags().testFlag(QNetworkInterface::CanBroadcast)
				&&interfaceItem.flags().testFlag(QNetworkInterface::CanMulticast)
				&&!interfaceItem.flags().testFlag(QNetworkInterface::IsLoopBack)
				&&interfaceItem.hardwareAddress()!="00:50:56:C0:00:01"
				&&interfaceItem.hardwareAddress()!="00:50:56:C0:00:08"
				&&
				(interfaceItem.humanReadableName()=="WLAN"
				||
				interfaceItem.humanReadableName()=="以太网"))
		{
			QList<QNetworkAddressEntry> addressEntryList=interfaceItem.addressEntries();
			foreach(QNetworkAddressEntry addressEntryItem, addressEntryList)
			{
				if(addressEntryItem.ip().protocol()==QAbstractSocket::IPv4Protocol)
				{
//					qDebug()<<"------------------------------------------------------------";
//					qDebug()<<"Adapter Name:"<<interfaceItem.name();
//					qDebug()<<"Adapter Name:"<<interfaceItem.index();
//					qDebug()<<"Adapter Name:"<<interfaceItem.humanReadableName();
//					qDebug()<<"Adapter Address:"<<interfaceItem.hardwareAddress();
//					qDebug()<<"IP Address:"<<addressEntryItem.ip().toString();
//					qDebug()<<"IP Mask:"<<addressEntryItem.netmask().toString();
//					qDebug()<<"IP interfaceItem.hardwareAddress():"<<interfaceItem.hardwareAddress();

					strIpAddress = addressEntryItem.ip().toString();
				}
			}
		}
	}

	 return strIpAddress;
}


QString TCPFile::gethostMac()
{
	QString strMacAddr = "";

	QList<QNetworkInterface> interfaceList = QNetworkInterface::allInterfaces();
	foreach(QNetworkInterface interfaceItem, interfaceList)
	{
		if(interfaceItem.flags().testFlag(QNetworkInterface::IsUp)
				&&interfaceItem.flags().testFlag(QNetworkInterface::IsRunning)
				&&interfaceItem.flags().testFlag(QNetworkInterface::CanBroadcast)
				&&interfaceItem.flags().testFlag(QNetworkInterface::CanMulticast)
				&&!interfaceItem.flags().testFlag(QNetworkInterface::IsLoopBack)
				&&interfaceItem.hardwareAddress()!="00:50:56:C0:00:01"
				&&interfaceItem.hardwareAddress()!="00:50:56:C0:00:08"
				&&
				(interfaceItem.humanReadableName()=="WLAN"
				||
				interfaceItem.humanReadableName()=="以太网"))
		{
			QList<QNetworkAddressEntry> addressEntryList=interfaceItem.addressEntries();
			foreach(QNetworkAddressEntry addressEntryItem, addressEntryList)
			{
				if(addressEntryItem.ip().protocol()==QAbstractSocket::IPv4Protocol)
				{
//					qDebug()<<"------------------------------------------------------------";
//					qDebug()<<"Adapter Name:"<<interfaceItem.name();
//					qDebug()<<"Adapter Name:"<<interfaceItem.index();
//					qDebug()<<"Adapter Name:"<<interfaceItem.humanReadableName();
//					qDebug()<<"Adapter Address:"<<interfaceItem.hardwareAddress();
//					qDebug()<<"IP Address:"<<addressEntryItem.ip().toString();
//					qDebug()<<"IP Mask:"<<addressEntryItem.netmask().toString();
//					qDebug()<<"IP interfaceItem.hardwareAddress():"<<interfaceItem.hardwareAddress();

					strMacAddr = interfaceItem.hardwareAddress();
				}
			}
		}
	}


	return strMacAddr;
}
